package com.sun.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.common.ExcelListener;
import com.sun.common.Result;
import com.sun.common.SystemCrmlog;
import com.sun.dto.DrugDto;
import com.sun.dto.ExcelStateDataVo;
import com.sun.entity.Category;
import com.sun.entity.Drug;
import com.sun.service.CategoryService;
import com.sun.service.DrugService;
import com.sun.service.DrugSupplierService;
import com.sun.service.SupplierService;
import com.sun.utils.JsonUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Project: hospitalDrugInformationManagement
 * @Author: 86178
 * @Date: 2023/3/1 19:36
 * @FileName: DrugController
 * @Description: ""
 */
@CrossOrigin
@RestController
@RequestMapping("/drug")
public class DrugController {
    @Autowired
    private DrugService drugService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private DrugSupplierService drugSupplierService;

    @Autowired
    private ExcelStateDataVo excelStateDataVo;


    /**
     * 查询所有药品
     *
     * @param
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/getDrugList")
    public Result<List<Drug>> getDrugList() {
        List<Drug> list = drugService.list();
        return Result.success(list);
    }

    /**
     * 新增药品信息
     *
     * @param drug
     * @return
     */
    @SystemCrmlog(title = "药品信息管理模块", type = "INSERT", description = "新增药品信息")
    @RequiresAuthentication
    @PostMapping
    public Result<String> save(@RequestBody Drug drug) {
        drugService.save(drug);
        return Result.success("新增药品信息成功");
    }

    /**
     * 批量新增药品信息
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result<ExcelStateDataVo> upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), DrugDto.class, new ExcelListener(drugService, categoryService, supplierService, excelStateDataVo, drugSupplierService)).sheet().doRead();
        return Result.success(excelStateDataVo);
    }

    /**
     * 导出为Excel
     *
     * @param response
     * @throws IOException
     */
    @RequiresAuthentication
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        List<DrugDto> data = drugService.selectAll();

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("药品信息表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), DrugDto.class).autoCloseStream(Boolean.FALSE).sheet("药品信息")
                    .doWrite(data);
        } catch (Exception e) {
            System.out.println("1111111111");
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JsonUtils.getBeanToJson(map));
        }
    }


    /**
     * 删除药品信息
     *
     * @param drugId
     * @return
     */
    @SystemCrmlog(title = "药品信息管理模块", type = "DELETE", description = "删除药品信息")
    @RequiresAuthentication
    @DeleteMapping("/{drugId}")
    public Result<String> delete(@PathVariable Long drugId) {
        drugService.removeById(drugId);
        return Result.success("药品信息删除成功");
    }

    /**
     * 修改药品信息
     *
     * @param drug
     * @return
     */
    @SystemCrmlog(title = "药品信息管理模块", type = "UPDATE", description = "修改药品信息")
    @RequiresAuthentication
    @PutMapping
    public Result<String> update(@RequestBody Drug drug) {
        drugService.updateById(drug);
        return Result.success("药品信息修改成功");
    }

    /**
     * 设置库存下限
     *
     * @param drug
     * @return
     */
    @SystemCrmlog(title = "库存管理模块", type = "UPDATE", description = "对某一药品设置库存下限")
    @RequiresAuthentication
    @PutMapping("/setTheInventoryFloor")
    public Result<String> setTheInventoryFloor(@RequestBody Drug drug) {
        drugService.updateById(drug);
        return Result.success("库存下限修改成功");
    }

    /**
     * 分页查询药品信息
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/page")
    public Result<Page> page(int pageNum, int pageSize, String drugName, String drugCode, Long categoryId) {
        Page<Drug> pageInfo = new Page<>(pageNum, pageSize);
        Page<DrugDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Drug> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        //根据药品名称
        lambdaQueryWrapper.like(null != drugName, Drug::getDrugName, drugName);
        //根据药品代码
        lambdaQueryWrapper.like(null != drugCode, Drug::getDrugCode, drugCode);
        //根据药品分类
        lambdaQueryWrapper.eq(null != categoryId, Drug::getCategoryId, categoryId);
        //根据药品厂商分类
        //lambdaQueryWrapper.eq(null != drug.getSupplierId(), Drug::getSupplierId,drug.getSupplierId());
        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Drug::getDrugName);
        drugService.page(pageInfo, lambdaQueryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Drug> records = pageInfo.getRecords();

        List<DrugDto> list = records.stream().map((item) -> {
            DrugDto drugDto = new DrugDto();
            //对象拷贝
            BeanUtils.copyProperties(item, drugDto);
            //分类id
            Long categoryId2 = item.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId2);
            if (category != null) {
                //分类名称
                String categoryName = category.getName();
                drugDto.setCategoryName(categoryName);
            }
            //厂商id
            //Long supplierId = item.getSupplierId();
            //根据分类id查询分类对象
//            Supplier supplier = supplierService.getById(supplierId);
//            if(supplier != null){
//                //分类名称
//                String supplierName = supplier.getSupplierName();
//                drugDto.setSupplierName(supplierName);
//            }
            return drugDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return Result.success(dtoPage);
    }


    /**
     * 查询药品总共有多少种，每种分类有多少种，总的库存多少，每种分类的库存多少。（柱状图）
     */
    @GetMapping("/getList")
    public Result getList() {
        drugService.selectDrug();
        return null;
    }
}
